<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="./../bootstrap/css/bootstrap.css">
</head>

<body>
  <div class="container">
    <div class="row">
      <div class="col">
        <h1 class="header">医生职称管理：</h1>
        <div class="my-5">
          <button class="btn btn-primary" type="button" id="addJobBtn">添加职称</button>
        </div>
        <div>
          <table class="table table-hover">
            <thead>
              <tr>
                <th>序号</th>
                <th>职称名称</th>
                <th>职称描述</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody id="jobTable">
              <tr>
                <td></td>
                <td></td>
                <td></td>
                <td>
                  <button type="button" class="btn btn-waring btn-edit">修改</button>
                  <button type="button" class="btn btn-danger btn-delete">删除</button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
  <!-- 添加 -->
  <div class="modal" tabindex="-1" id="addJobModal">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">添加职称</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <form>
            <div class="form-group">
              <label for="jobname">职称名称：</label>
              <input type="email" name="jobname" class="form-control" id="jobname" aria-describedby="emailHelp">
              <small id="jobnamehelp" class="form-text text-muted">请输入20字以内得职称名称</small>
            </div>
            <div class="form-group">
              <label for="jobdes">职称描述：</label>
              <input type="text" class="form-control" id="jobdes">
              <small id="jobdeshelp" class="form-text text-muted">请输入50字以内得职称描述</small>

            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
          <button type="button" class="btn btn-primary btn-add">添加</button>
        </div>
      </div>
    </div>
  </div>
</body>
<script src="./../jquery/jquery 3.5.1.js"></script>
<script src="./../bootstrap/js/bootstrap.bundle.js"></script>
<script>
  window.onload = function () {
    getJobsData();
  };
  const getJobsData = function () {
    // 1.创建ajax核心对象
    // console.log(window.XMLHttpRequest)
    let xhr;
    if (window.XMLHttpRequest) {//非IE
      xhr = new XMLHttpRequest()
    } else { // IE
      xhr = new ActiveObject('Microsoft.XMLHTTP')
    }
    // 配置对象：
    // xhr.open('get|post', url?key=value, 同步|异步)
    xhr.open('get', "/getJobs", true);
    xhr.send(null)  // get请求时，参数不写在send()中，而是再url?key=V;

    // 等待后台回复数据得事件监听
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4 && xhr.status === 200) {
        console.log('请求成功')
        let textData = xhr.responseText; // 获取后端得响应数据，数据是字符串。
        // console.log(textData) // JSON字符串， 需要转换程json对象格式。

        let result = JSON.parse(textData)
        console.log(result)

        if (result.code === 200) {
          // alert(result.msg);
          // 更新表格
          let jobTable = document.querySelector("#jobTable")
          jobTable.innerHTML = ""
          let strHtml = '';
          result.data.forEach((el, index) => {
            strHtml += `<tr>
                <td>${index + 1}</td>
                <td>${el.jname}</td>
                <td>${el.jdes}</td>
                <td>
                  <button type="button" class="btn btn-warning btn-edit" data-id="${el.jid}">修改</button>
                  <button type="button" class="btn btn-danger btn-delete" data-id="${el.jid}">删除</button>
                </td>
              </tr>`;
          });
          jobTable.innerHTML = strHtml;
        } else {
          alert(result.msg);
        }
      }
    }
  }

  // 事件委托：
  document.getElementById('jobTable').onclick = function (event) {
    // console.log(event.target)
    if (event.target.className.includes('btn-edit')) {
      // alert('点击编辑')
    } else if (event.target.className.includes('btn-delete')) {
      // alert('点击删除')
      let jid = event.target.getAttribute('data-id')
      deleteJobsHandler(jid);
    }
  }

  // 添加职称显示modal
  $('#addJobBtn').on('click', function () {
    $("#addJobModal").modal('show')
  })

  // 保存添加得职称数据
  $('.btn-add').on('click', function () {
    let jobname = $("#jobname").val();
    let jobdes = $("#jobdes").val();

    // 省略正则验证。。。，如果验证通过，就发起AJAX请求
    let xhr = null;
    if (window.XMLHttpRequest) {
      xhr = new XMLHttpRequest()
    } else {
      xhr = new ActiveXObject('Microsoft.XMLHTTP')
    }
    xhr.open('get', `/addJobs?jobname=${jobname}&jobdes=${jobdes}`, true);
    xhr.send()
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4 && xhr.status === 200) {
        let text = xhr.responseText;
        let res = JSON.parse(text)
        console.log(res)
        if (res.code === 200) {
          // alert('添加成功')
          $("#addJobModal").modal('hide')
          getJobsData(); //重修调用接口，动态渲染表格
        } else {
          alert('添加失败')
        }
      }
    }

  });

  // 删除职称
  const deleteJobsHandler = function (jid) {
    console.log(jid)

    // ajax post:
    let xhr = null;
    if (window.XMLHttpRequest) {
      xhr = new XMLHttpRequest()
    } else {
      xhr = new ActiveXObject('Microsoft.XMLHTTP')
    }
    /* post时，url不拼接参数，send()里面放参数 ，
    必须写请求头信息。 xhr.setRequestHeader（）；
    */
    xhr.open('post', '/deleteJobs', true)
    // xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded") // 设置请求头为普通的表单提交数据的编码格式。
    // xhr.send(`jid=${jid}`);
    // 如果参数很多个，可以传json对象，
    xhr.setRequestHeader("Content-type", "application/json;charset=UTF-8")
    // 必须把对象转为json字符串，后端才能拿到参数。
    xhr.send(JSON.stringify({ 'jid': jid }))

    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4 && xhr.status === 200) {
        let text = xhr.responseText;
        let res = JSON.parse(text)
        console.log(res)
        if (res.code === 200) {
          alert('删除成功')
          getJobsData(); //重修调用接口，动态渲染表格
        } else {
          alert('添加失败')
        }
      }
    }

  }



</script>

</html>